package com.ziqikeji.concurrent.server.rest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author dpf
 */
@RestController
@RequestMapping("concurrent")
public class ConcurrentRestController {
    private static int size = 10;

    @RequestMapping("index")
    public int index(@RequestParam("threadName") String threadName) {
        System.out.println(threadName + "开始消费，剩余资源数：" + size);

        int result = 0;

        if (size > 0) {
            Random rand = new Random(25);
            int random = rand.nextInt(10000);
            try {
                Thread.sleep(random);
            } catch (InterruptedException e) {
                System.out.println("线程异常");
            }
            synchronized (this) {
                size = size - 1;
                result = size;
            }
            System.out.println(threadName + "消费完，剩余资源数：" + result);

        } else {
            System.out.println("资源消耗完");
        }
        return result;
    }
}
